#include "pwm.h"

#define CTIMER          CTIMER0         /* Timer 0 */
#define CTIMER_MAT_OUT  kCTIMER_Match_1 /* Match output 1 */
#define CTIMER_CLK_FREQ CLOCK_GetFreq(kCLOCK_CoreSysClk)
#define CTIMER_MAT_PWM_PERIOD_CHANNEL kCTIMER_Match_3

static void PWM_Init(void);
static void PWM_UpdateDuty(uint8_t percent);

PWM_t PWM = {
		.init = PWM_Init,
		.updateduty = PWM_UpdateDuty,
};


volatile uint32_t g_pwmPeriod   = 0U;
volatile uint32_t g_pulsePeriod = 0U;


status_t CTIMER_GetPwmPeriodValue(uint32_t pwmFreqHz, uint8_t dutyCyclePercent, uint32_t timerClock_Hz)
{
    /* Calculate PWM period match value */
    g_pwmPeriod = (timerClock_Hz / pwmFreqHz) - 1U;

    /* Calculate pulse width match value */
    g_pulsePeriod = (g_pwmPeriod + 1U) * (100 - dutyCyclePercent) / 100;

    return kStatus_Success;
}

static void PWM_Init(void)
{
		ctimer_config_t config;
    uint32_t srcClock_Hz;
    uint32_t timerClock;
	
		srcClock_Hz = CTIMER_CLK_FREQ;
	
		CTIMER_GetDefaultConfig(&config);
    timerClock = srcClock_Hz / (config.prescale + 1);

    CTIMER_Init(CTIMER, &config);

    /* Get the PWM period match value and pulse width match value of 20Khz PWM signal with 20% dutycycle */
    CTIMER_GetPwmPeriodValue(20000, 90, timerClock);
    CTIMER_SetupPwmPeriod(CTIMER, CTIMER_MAT_PWM_PERIOD_CHANNEL, CTIMER_MAT_OUT, g_pwmPeriod, g_pulsePeriod, false);
    CTIMER_StartTimer(CTIMER);
	
}

static void PWM_UpdateDuty(uint8_t percent)
{
		assert(percent>=0 && percent<=100);
		CTIMER_UpdatePwmDutycycle(CTIMER, CTIMER_MAT_PWM_PERIOD_CHANNEL, CTIMER_MAT_OUT,percent);
}








